<?php

namespace App\Http\Controllers\wechat\users;

use App\Http\Controllers\Controller;
use App\Models\news\NewsListModel;
use App\Models\users\UsersAmountRecordModel;
use App\Models\users\UsersBankModel;
use App\Models\users\UsersNewProductRecordModel;
use App\Models\users\UsersSettingModel;
use App\Models\users\UsersWithdrawOrderModel;
use App\Service\users\UsersSaveService;
use App\Service\users\UsersService;
use App\Service\users\WithdrawService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use lxs\api\ApiResponse;
use lxs\tools\Tools;

class UsersController extends Controller
{

    /**
     * 获取首页用户系统页面数据
     */
    public function getHomeUserSystemData(Request $request): JsonResponse
    {

        $uid = $request->uid;

        $config['user_prr'] = Tools::Config('SYSTEM.prr');
        $config['is_news'] = NewsListModel::where('uid', $uid)->where('deleted_at', 0)->where('is_browse', 0)->count();

        $userInfo = UsersService::instance()->getUserInfo($uid);
        if (!$userInfo) {
            return ApiResponse::apiResponseData(100, '获取用户信息失败');
        }
        // 今日收益
        $userInfo->todayIncome = UsersAmountRecordModel::where('uid', $uid)
            ->whereBetween('create_time', [strtotime(date("Y-m-d {$config['user_prr']}")), time()])
            ->sum('num');
        // 今日拉新
        $userInfo->todayNew = UsersNewProductRecordModel::where('uid', $uid)
            ->whereBetween('create_time', [strtotime(date("Y-m-d {$config['user_prr']}")), time()])
            ->count();

        return ApiResponse::apiResponseData(200, '获取首页用户系统页面数据成功', [
            'config' => $config,
            'user_info' => $userInfo
        ]);
    }


    /**
     * 获取用户信息
     */
    public function getUserInfoData(Request $request): JsonResponse
    {

        $userInfo = UsersService::instance()->getUserInfo($request->uid);

        if ($userInfo) {
            return ApiResponse::apiResponseData(200, '获取用户信息成功', [
                'user_info' => $userInfo,
            ]);
        }
        return ApiResponse::apiResponseData(400, '获取用户信息失败');
    }


    /**
     * 获取用户详细信息
     */
    public function getUserDetailData(Request $request): JsonResponse
    {

        $userInfo = UsersService::instance()->getUserDetail($request->uid);

        if ($userInfo) {
            $userInfo->withdraw_commission = Tools::Config('USER.withdraw_commission');
            return ApiResponse::success('获取用户详细信息成功', [
                'user_info' => $userInfo,
            ]);
        }
        return ApiResponse::error('获取用户详细信息失败');
    }


    /**
     * 获取用户设置
     */
    public function getUserSettingData(Request $request): JsonResponse
    {

        $userSetting = UsersSettingModel::where('uid', $request->uid)->first();

        if (!$userSetting) {
            $userSetting = new UsersSettingModel([
                'uid' => $request->uid,
                'create_time' => time(),
            ]);
            $userSetting->save();
        }

        $userBank = UsersBankModel::where('uid', $request->uid)->first();

        return ApiResponse::apiResponseData(200, '获取用户设置成功', [
            'user_setting' => $userSetting,
            'user_bank' => $userBank,
        ]);
    }


    /**
     * 用户开关设置
     */
    public function setUserSwitch(Request $request): JsonResponse
    {

        $name = $request->input('name');
        $value = $request->input('value');
        $userInfo = UsersService::instance()->getUserInfo($request->uid);

        $userInfo->userSetting->update([$name => $value]);

        return ApiResponse::apiResponseData(200, '设置成功');
    }


    /**
     * 用户设置表单提交
     */
    public function userSettingSubmit(Request $request): JsonResponse
    {
        $formData = $request->input();
        try {
            $result = UsersSaveService::instance()->saveBankCard($request->uid, $formData);
            return ApiResponse::success($result['message']);
        } catch (\Exception $e) {
            return ApiResponse::error('绑定失败');
        }
    }


    /**
     * 获取注销账号页面数据
     */
    public function getCancelAccountData(Request $request): JsonResponse
    {
        $content = Tools::Config('SINGLE.cancel_account_content');

        return ApiResponse::apiResponseData(200, '获取成功', [
            'content' => $content,
        ]);
    }


    /**
     * 确定注销账号提交
     */
    public function cancelAccountSubmit(Request $request): JsonResponse
    {

        $userInfo = UsersService::instance()->getUserInfo($request->uid);

        if ($userInfo->amount > 0 || $userInfo->credit > 0) {
            $tips = [
                'message' => '申请注销失败',
                'content' => '为了保护您的账户安全，我们建议您在完成所有提现操作后再进行账户注销。如果在提现过程中遇到任何问题，或者您需要进一步的帮助，请随时联系我们的客服团队。',
                'height' => 600
            ];
            return ApiResponse::error('您的账户还有余额', 204, ['tips' => $tips]);
        }
        $userInfo->update([
            'is_cancel' => 1,
            'cancel_time' => time(),
        ]);
        $tips = [
            'message' => '您的账户已提交注销申请',
            'content' => '请注意，该账号注销有30天的冷静期(账号锁定期)。除法律法规规定和注销协议约定情形外，我们将在冷静期满后完成注销，在冷静期内登录该账号即视为取消注销流程。您将在点击确认后退出该账号。',
            'height' => 600
        ];
        return ApiResponse::success('您已成功提交注销申请！', ['tips' => $tips]);

    }


    /**
     * 实名认证表单提交
     */
    public function userAuthenticationSubmit(Request $request): JsonResponse
    {
        $formData = $request->input();
        $uid =  $request->uid;

        $validator = Validator::make($formData, [
            'realname' => ['required'],
            'mobile' => ['required',
                function ($attribute, $value, $fail) {
                    if (!preg_match('/^1[3-9]\d{9}$/', $value)) {
                        $fail('手机号码格式不正确');
                    }
                }
            ],
            'id_card' => ['required',
                function ($attribute, $value, $fail) {
                    if (!preg_match('/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/', $value)) {
                        $fail('身份证号码格式不正确');
                    }
                }
            ],
        ], [
            'realname.required' => '请输入真实姓名',
            'mobile.required' => '请输入手机号码',
            'id_card.required' => '请输入身份证号码',
        ]);

        if ($validator->fails()) {
            return ApiResponse::apiResponseData(5006, $validator->errors()->first());
        }

        $result = UsersSaveService::instance()->saveRealName($uid, $formData);
        if ($result['code'] == 200) {
            return ApiResponse::success($result['message']);
        }
        return ApiResponse::error($result['message']);
    }


    /**
     * 用户提现表单提交
     */
    public function userWithdrawSubmit(Request $request): JsonResponse
    {
        $formData = $request->input();
        $uid = $request->uid;
        $result = WithdrawService::instance()->userWithdrawSubmit($uid, $formData);
        if ($result['code'] == 200) {
            return ApiResponse::success('提交成功', $result['data']);
        }
        return ApiResponse::error($result['message'], $result['code']);
    }


    /**
     * 获取体现提交成功页面数据
     */
    public function getWithdrawSuccessData(Request $request): JsonResponse
    {
        $withdraw_id = $request->input('withdraw_id');
        $withdrawInfo = UsersWithdrawOrderModel::where('id', $withdraw_id)->first();
        if (!$withdrawInfo) {
            return ApiResponse::apiResponseData(400, '提现信息不存在');
        }
        return ApiResponse::apiResponseData(200, '获取成功', [
            'info' => $withdrawInfo,
        ]);
    }


    /**
     * 获取用户收益明细页面数据
     */
    public function getUserIncomeData(Request $request): JsonResponse
    {

        $page = $request->input('page');
        $pageSize = $request->input('page_size');
        $dateTime = $request->input('dateTime');
        $type = $request->input('type');
        $uid = $request->uid;

        $userInfo = UsersService::instance()->getUserBalance($uid);

        list ($lists, $count) = UsersService::instance()->getUserIncomeRecordData($uid, $page, $pageSize, $dateTime, $type);

        return ApiResponse::apiResponseData(200, '获取用户收益明细页面数据成功', [
            'userInfo' => $userInfo,
            'lists' => $lists,
            'total' => $count,
        ]);
    }


    /**
     * 产品详情页弹窗已观看更改状态
     */
    public function productDetailPopupWatch(): JsonResponse
    {
        $uid = request()->uid;
        try {
            $userInfo = UsersService::instance()->getUserInfo($uid);
            $userInfo->update([
                'product_watch' => 1,
            ]);
            return ApiResponse::apiResponseData(200, '操作成功');
        } catch (\Exception $e) {
            return ApiResponse::apiResponseData(400, '操作失败');
        }
    }


}
